﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using EvertonApp.AdminWeb.Models;
using EvertonApp.Transporte;
using Newtonsoft.Json;
using RestSharp;
using RestSharp.Deserializers;

namespace EvertonApp.AdminWeb.Controllers
{
    class ApiProxy
    {
        private const string BaseUrl = "http://localhost:8080";

        readonly string _accountSid;
        readonly string _secretKey;

        public ApiProxy()
        {
        }

        public ApiProxy(string accountSid, string secretKey)
        {
            _accountSid = accountSid;
            _secretKey = secretKey;
        }

        public IRestResponse Execute(RestRequest request)
        {
            var client = new RestSharp.RestClient();
            client.BaseUrl = BaseUrl;

            var response = client.Execute(request);

            //Para usar cuando implementemos la autentificación
            //client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
            //request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment); // used on every request

            if (response.ErrorException != null)
            {
                const string message = "Error retrieving response.  Check inner details for more info.";
                throw new ApplicationException(message, response.ErrorException);
            }

            return response;

        }

        public T Execute<T>(RestRequest request) where T : new()
        {
            var client = new RestSharp.RestClient();
            client.BaseUrl = BaseUrl;

            //Para usar cuando implementemos la autentificación
            //client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
            //request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment); // used on every request

            var response = client.Execute<T>(request);

            if (response.ErrorException != null)
            {
                const string message = "Error retrieving response.  Check inner details for more info.";
                throw new ApplicationException(message, response.ErrorException);
            }

            return response.Data;
        }

        public List<T> ExecuteList<T>(RestRequest request) where T : new()
        {
            var client = new RestSharp.RestClient();
            client.BaseUrl = BaseUrl;


            //Para usar cuando implementemos la autentificación
            //client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
            //request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment); // used on every request

            var response = client.Execute<T>(request);

            List<T> myResults;

            using (Stream ms2 = new MemoryStream(Encoding.UTF8.GetBytes(response.Content)))
            {
                myResults = JsonConvert.DeserializeObject<List<T>>(new StreamReader(ms2).ReadToEnd());
            }

            return myResults;
        }

        public List<Comercio> ObtenerComercios()
        {
            var request = new RestRequest();
            request.AddHeader("Content-Type", "application/json");
            request.RequestFormat = DataFormat.Json;
            request.Resource = "/api/comercio";
            request.RootElement = "Comercio";


            var response = ExecuteList<Comercio>(request);

            return response;
        }

        public Comercio ObtenerComercio(Guid id)
        {
            var request = new RestRequest();
            //comprobar si funciona
            request.AddHeader("Content-Type", "application/json");
            request.RequestFormat = DataFormat.Json;

            request.AddParameter("id", id);
            request.Resource = "/api/comercio";
            request.RootElement = "Comercio";


            var response = Execute<Comercio>(request);

            return response;
        }

        public bool CrearComercio(ComercioModel value)
        {
            Comercio comercio = new Comercio{IdComercio =  value.Id, Direccion = value.Direccion, Nombre = value.Nombre, Telefono = value.Telefono};

            var request = new RestRequest();
            request.AddHeader("Content-Type", "application/json");
            request.RequestFormat = DataFormat.Json;

            request.Resource = "/api/comercio";
            request.AddObject(comercio);
            request.Method = Method.POST;

            var response = Execute(request);
            return true;
        }






        //// POST api/comercio
        //public void Post([FromBody]Comercio value)
        //{
        //    _comercios.ComerciosRepository.Insert(value);
        //}

        //// PUT api/comercio/5
        //public void Put(Guid id, [FromBody]Comercio value)
        //{
        //    _comercios.ComerciosRepository.Update(id, value);
        //}

        //// DELETE api/comercio/5
        //public bool Delete(Guid id)
        //{
        //    try
        //    {
        //        _comercios.ComerciosRepository.Delete(_comercios.ComerciosRepository.GetById(id));
        //        return true;
        //    }
        //    catch (Exception)
        //    {
        //        return false;
        //    }
        //}


    }
}
